<template>
  <div class="content-section user-section">
    <div class="section-header">
      <div class="section-title-container">
        <h2 class="section-title">
          <span class="title-icon">👤</span>
          个人信息
        </h2>
        <p class="section-subtitle">管理您的个人资料和账户信息</p>
      </div>
      <div class="profile-actions">
        <!--        <button class="btn-form btn-secondary" @click="resetProfile">重置</button>-->
        <button class="btn-style" style="padding: 0.5rem 1.88rem" @click="updateProfile"
          >保存</button
        >
      </div>
    </div>

    <n-form ref="formRef" :model="userInfo" :rules="rules">
      <n-form-item
        path="avatar"
        label="头像"
        label-style="color: #374151;
      fontSize: 15px;fontWeight: 600;"
      >
        <div class="avatar-upload">
          <n-upload
            :action="`${apiUrl}/system/oss/upload`"
            :headers="uploadHeaders"
            :max-number="1"
            :show-file-list="false"
            :on-finish="avatarUploadChange"
          >
            <div class="avatar-container">
              <img :src="userInfo.avatar || websiteConfig.userImage" alt="头像" class="avatar" />
              <div class="avatar-overlay">
                <n-icon size="20" color="#ffffff">
                  <Camera />
                </n-icon>
                <span class="upload-text">更换头像</span>
              </div>
            </div>
          </n-upload>
          <p class="upload-tip" @click.stop="() => {}">支持 JPG、PNG 格式，建议尺寸 200x200px</p>
        </div>
      </n-form-item>
      <n-form-item
        path="username"
        label="昵称"
        label-style="color: #374151;
      fontSize: 15px;fontWeight: 600;"
      >
        <input
          v-model="userInfo.username"
          type="text"
          class="form-input"
          placeholder="请输入昵称"
        />
      </n-form-item>
      <n-form-item
        path="phone"
        label="手机号"
        label-style="color: #374151;
      fontSize: 15px;fontWeight: 600;"
      >
        <input
          v-model="userInfo.phone"
          type="tel"
          class="form-input"
          placeholder="请输入手机号码"
        />
      </n-form-item>
      <n-form-item
        path="email"
        label="邮箱"
        label-style="color: #374151;
      fontSize: 15px;fontWeight: 600;"
      >
        <input
          v-model="userInfo.email"
          type="email"
          class="form-input"
          placeholder="请输入邮箱地址"
        />
      </n-form-item>
    </n-form>
  </div>
</template>

<script setup>
  import { Camera } from '@vicons/ionicons5';
  import { ref, computed, onMounted, reactive } from 'vue';
  import { useUserStore } from '@/store/modules/user';
  import { useGlobSetting } from '@/hooks/setting';
  import { updateUserInfoApi } from '@/api/system/user';
  import { useMessage } from 'naive-ui';
  import { websiteConfig } from '@/config/website.config';

  // 用户信息
  const userStore = useUserStore();
  const token = userStore.getToken;

  const formRef = ref(null);
  const message = useMessage();

  const { apiUrl } = useGlobSetting();
  const uploadList = ref([]);
  const uploadHeaders = reactive({
    Authorization: token,
  });

  const userInfo = ref({
    username: '',
    avatar: '',
    phone: '',
    email: '',
  });

  const updateProfile = () => {
    formRef.value.validate(async (errors) => {
      if (!errors) {
        try {
          await updateUserInfoApi(userInfo.value);
          await userStore.getInfo();
          message.success('更新成功');
        } finally {
          console.log('更新成功');
        }
      } else {
        message.error('请填写完整信息');
      }
    });
  };

  const resetProfile = () => {
    userInfo.value = {
      id: '123456789',
      nickname: '学习达人',
      email: 'user@example.com',
      phone: '138****8888',
      bio: '热爱学习，追求进步',
      avatar: '/placeholder.svg?height=80&width=80',
    };
  };

  const rules = {
    username: {
      required: true,
      message: '请输入昵称',
      trigger: 'blur',
    },
    avatar: {
      required: true,
      message: '请输入昵称',
      trigger: 'blur',
    },
    phone: [
      {
        required: true,
        validator(rule, value) {
          if (!/^1[3456789]\d{9}$/.test(value)) {
            return new Error('请输入正确的手机号码');
          } else {
            return true;
          }
        },
        trigger: ['input', 'blur'],
      },
    ],
  };

  function avatarUploadChange(file) {
    userInfo.value['avatar'] = JSON.parse(file.event.target.response)?.data;
  }

  onMounted(() => {
    userInfo.value = JSON.parse(JSON.stringify(userStore.getUserInfo));
    uploadList.value = userInfo.value.avatar ? [userInfo.value.avatar] : [];
  });
</script>

<style lang="less" scoped>
  .profile-actions {
    .btn-secondary {
      background: rgba(248, 250, 252, 0.8);
      color: #64748b;
      border: 2px solid #e2e8f0;
      margin-right: 10px;

      &:hover {
        background: rgba(241, 245, 249, 0.9);
        border-color: #cbd5e1;
      }
    }
  }

  .avatar-upload {
    .avatar-container {
      position: relative;
      display: inline-block;

      .avatar {
        width: 120px;
        height: 120px;
        border-radius: 50%;
        object-fit: cover;
        border: 4px solid #d174df;
        box-shadow: 0 8px 24px rgba(209, 116, 223, 0.3);
        transition: all 0.3s ease;

        &:hover {
          transform: scale(1.05);
        }
      }

      .avatar-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(209, 116, 223, 0.9);
        border-radius: 50%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        opacity: 0;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          opacity: 1;
          transform: scale(1.05);
        }

        .upload-text {
          color: white;
          font-size: 12px;
          font-weight: 600;
        }
      }
    }

    .upload-tip {
      margin: 0;
      color: #64748b;
      font-size: 14px;
      line-height: 1.5;
    }
  }

  .form-input,
  .form-textarea {
    width: 100%;
    padding: 16px;
    border: 2px solid #e2e8f0;
    border-radius: 12px;
    font-size: 15px;
    transition: all 0.3s ease;
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);

    &:focus {
      outline: none;
      border-color: #d174df;
      box-shadow: 0 0 0 4px rgba(209, 116, 223, 0.1);
      background: white;
    }

    &::placeholder {
      color: #9ca3af;
    }
  }

  .form-textarea {
    min-height: 120px;
    resize: vertical;
    font-family: inherit;
  }
</style>
